﻿/*
   Copyright 2012 University of Southampton

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Data;
using System.IO;
using Microsoft.SharePoint.WebPartPages;
using uk.ac.soton.ses.DAL;

namespace uk.ac.soton.ses
{
    [ToolboxItemAttribute(false)]
    public class CtDataViewerWebPart : System.Web.UI.WebControls.WebParts.WebPart
    {
        // Visual Studio might automatically update this path when you change the Visual Web Part project item.
        private const string _ascxPath = @"~/_CONTROLTEMPLATES/uk.ac.soton.ses/HDCUserControls/CtDataViewerUserControl.ascx";

        private IHDCWebPartSelectedExperimentDataFileID _dataFileProvider = null;
        private ExperimentDataFile _experimentDataFile;
        private CtDataViewerUserControl _ctDataViewerUserControl;

        private void DisplayMessage(string error)
        {
            Label messageLabel = new Label();
            Controls.Add(messageLabel);
            messageLabel.Text = error;
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            this._ctDataViewerUserControl = (CtDataViewerUserControl)Page.LoadControl(_ascxPath);
            this._ctDataViewerUserControl.Visible = false;
            this.Controls.Add(_ctDataViewerUserControl);

        }
        /// <summary>
        /// Create controls on PreRender event. CreateChildControls would be nice, but it is sometimes
        /// called too early, before the data from row Provider web part has been sent
        /// </summary>
        /// <param name="e">Event data</param>
        protected override void OnPreRender(EventArgs e)
        {
            this.DebugMessage("ct>prerender");
            base.OnPreRender(e);
            if (this._dataFileProvider == null)
            {
                this._ctDataViewerUserControl.Visible = false;
                DisplayMessage("No provider in PreRender.");
            }
            else
            {
                int df = this._dataFileProvider.GetSelectedExperimentDataFileID();
                if (df == -1)
                {
                    this._ctDataViewerUserControl.Visible = false;
                    DisplayMessage("No data file selected.");
                }
                else
                {
                    MaterialsMetadataContext dbcontext = HttpContext.Current.GetMaterialsDBContext();
                    this._experimentDataFile = dbcontext.GetExperimentDataFileByID(df);
                    if (this._experimentDataFile != null)
                    {
                        this._ctDataViewerUserControl.Visible = true;
                        this._ctDataViewerUserControl.DataFileID = this._experimentDataFile.ID;
                    }
                    else
                    {
                        DisplayMessage("Couldn't load the selected Experiment");
                    }
                }
            }
        }

        protected override void RenderContents(HtmlTextWriter writer)
        {
            this.DebugMessage("Ct>RenderContents");
            base.RenderContents(writer);

            if (this._dataFileProvider == null)
            {
                writer.Write("Not connected");
            }
        }

        [ConnectionConsumer("SelectedExperimentDataFile")]
        public void SetExperimentDataFileConnectionInterface(IHDCWebPartSelectedExperimentDataFileID provider)
        {
            this._dataFileProvider = provider;
            if (_dataFileProvider == null)
            {
                DisplayMessage("No connection. Please connect me to an Experiment Data Files list.");
            }
        }

        private void DebugMessage(string s)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (FileStream fs = File.Open(@"c:\temp\debuglog.log", FileMode.Append, FileAccess.Write, FileShare.Read))
                using (StreamWriter writer = new StreamWriter(fs))
                {
                    writer.AutoFlush = true;
                    writer.WriteLine(s);
                    writer.Flush();
                    writer.Close();
                }
            });
        }
    }
}
